package org.gary.product.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static lengreen.util.constant.Constant.DateFomaterString.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.gary.base.model.Category;
import org.gary.base.model.Image;
import org.gary.base.service.CategoryService;
import org.gary.base.service.ImageService;
import org.gary.base.service.XxxImageService;
import org.gary.core.service.InitService;
import org.gary.core.util.Util;

import static org.gary.core.util.Utils.*;
import org.gary.product.model.Product;
import org.gary.product.service.ProductService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 产品action
 * 
 * @author lengreen
 * 
 */
@Component
@Scope("prototype")
public class ProductAction extends ActionSupport implements
		ServletResponseAware, ServletRequestAware, SessionAware {
	private static final long serialVersionUID = 9068378352800285968L;

	private HttpServletResponse response;
	private HttpServletRequest request;
	private Map<String, Object> session;
	private InitService initService;

	private XxxImageService xxxImageService;
	private ImageService imageService;
	private ProductService productService;
	private CategoryService categoryService;
	/** 记录单个产品信息 */
	private Product product;
	/** 记录产品列表信息 */
	private List<Product> productList;
	/** 记录当前页 */
	private int start;
	/** 记录分页最大记录条数 */
	private int limit;
	/** 记录产品名称 */
	private String productName;
	/** 开始时间 */
	private String fromDate;
	/** 结束时间 */
	private String toDate;
	/** 产品类别 */
	private String category;
	
	/** 记录产品每页最大条数 */
	private final int MAXPRODUCT = 12;

	/** 用于规定上传文件的大小 **/
	private static final int BUFFER_SIZE = 200 * 1024;
	private File[] productImage;
	/** 用String数组来封装多个上传文件名 **/
	private String[] productImageFileName;
	/** 用String数组来封装多个上传文件类型 **/
	private String[] productImageContentType;
	/** 删除模式 */
	private String mode;
	/** 删除谁 */
	private String who;
	/** 是否可见 */
	private String visible;
	/** 语言 */
	private String lang;
	private String result;

	/**
	 * 增加一个产品
	 * 
	 * @throws IOException
	 */
	public void add() throws IOException {
		if (product != null) {
			Set<Image> images = handleImagesUpload(productImage,
					productImageFileName, "ProductImage", BUFFER_SIZE);
			if (images != null) {
				product.setImages(images);
			}
			Category c = categoryService.loadCategoryByName(category, product
					.getLang());
			product.setCategory(c);
			productService.save(product);
			result = "{'success':'true'}";
		} else {
			result = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}

	/**
	 * 列出产品列表
	 * 
	 * @throws IOException
	 */
	public void list() throws IOException {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setProductList(productService.list(Product.class, start, limit, where,
				new Object[] { " entity.id desc " }));

		for (Product p : productList) {
			System.out.println("pppp-->" + p);
		}

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[]{"notes", "visible", "images"});
		JSONArray productListJsonArray = JSONArray.fromObject(productList, config);
		JSONObject productJsonObject = new JSONObject();
		productJsonObject.put("productTotal", productService
				.selectTotalCount(null));
		productJsonObject.put("productList", productListJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(productJsonObject.toString());
	}

	/**
	 * 搜索产品
	 * 
	 * @throws IOException
	 */
	public void search() throws IOException {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setCategory(new String(category.getBytes("iso8859-1"), "utf-8"));

		System.out.println("productName-->" + productName);
		System.out.println("fromDate-->" + fromDate);
		System.out.println("toDate-->" + toDate);
		System.out.println("category-->" + category);

		if (!"".equals(productName.trim())) {
			where.put(" entity.name like ", productName);
		}
		if (!"".equals(fromDate.trim())) {
			if ("".equals(toDate.trim())) {
				where.put(" entity.createDate between ", fromDate
						+ " 00:00:00' and '"
						+ getFormatDate(new Date(), YYYY_MM_DD_HH_MM_SS));
			} else {
				where.put(" entity.createDate between ", fromDate
						+ " 00:00:00' and '" + toDate + " 23:59:59");
			}
		}
		if (!"".equals(category.trim())) {
			where.put(" entity.category.name = ", "'" + category + "'");
		}
		if (!"".equals(lang.trim())) {
			where.put(" entity.lang = ", lang);
		}

		setProductList(productService.list(Product.class, start, limit, where,
				new Object[] { " entity.id desc " }));

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[]{"notes", "visible", "images"});
		JSONArray productListJsonArray = JSONArray.fromObject(productList, config);
		JSONObject productJsonObject = new JSONObject();
		productJsonObject.put("productTotal", productService
				.selectTotalCount(null));
		productJsonObject.put("productList", productListJsonArray);
		System.out.println("productJsonObject-->"
				+ productJsonObject.toString());
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(productJsonObject.toString());
	}

	/**
	 * 加载一个产品
	 * 
	 * @throws IOException
	 */
	public void load() throws IOException {
		Product p = productService.load(Product.class, product.getId());
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "category.parent",
				"category.children", "images" });
		JSONObject productJsonObject = JSONObject.fromObject(p, config);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(productJsonObject.toString());
	}

	/**
	 * 加载关联图片
	 * 
	 * @throws IOException
	 */
	public void loadImages() throws IOException {
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "createDate", "visible", "id" });
		JSONArray imagesJsonArray = JSONArray.fromObject(productService
				.loadImages(product.getId()), config);
		JSONObject imagesJsonObject = new JSONObject();
		imagesJsonObject.put("images", imagesJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(imagesJsonObject.toString());
	}

	/**
	 * 更新产品
	 * 
	 * @throws IOException
	 */
	public void update() throws IOException {
		if (product != null) {
			Set<Image> images = handleImagesUpload(productImage,
					productImageFileName, "ProductImage", BUFFER_SIZE);
			if (images == null) {
				images = new HashSet<Image>();
			}
			for (Image i : productService.loadImages(product.getId())) {
				images.add(i);
			}
			product.setImages(images);

			Category c = categoryService.loadCategoryByName(category, product
					.getLang());
			product.setCategory(c);
			productService.update(product);
			result = "{'success':'true'}";
		} else {
			result = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}

	/**
	 * 删除产品
	 * 
	 * @throws IOException
	 */
	public void delete() throws IOException {
		try {
			if ("delete".equals(getMode())) {
				Object[] imageIds = xxxImageService.deleteByXxxId(getWho(),
						product.getId());
				if (imageIds.length > 0) {
					imageService.delete(Image.class, imageIds);
				}
				productService.delete(product);
				result = "{'result':'delete'}";
			} else if ("update".equals(getMode())) {
				productService.update(Product.class, new Object[] { product
						.getId() }, false);
				result = "{'result':'update'}";
			} else {
				result = "{'result':'none'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// --------------------------------------------------------------------------------

	public String productList() {
		initService.initAll(session);
		
		List<Product> banner=productService.getProductList(10,0,session.get("WW_TRANS_I18N_LOCALE"),-1);
		request.setAttribute("banner", banner);	
		
		String productType = request.getParameter("productType");
		List<Product> productList = null;
		int productCurrentPage;
		String productPage = request.getParameter("productPage");
		if (productPage != null) {
			productCurrentPage = Integer.parseInt(productPage);
		} else {
			productCurrentPage = 0;
		}

		// 得到分页bean
		Util u = new Util("product", MAXPRODUCT, session.get("WW_TRANS_I18N_LOCALE"));
		if (productType == null) {
			productList = productService.getProductList(MAXPRODUCT, productCurrentPage, session
					.get("WW_TRANS_I18N_LOCALE"), -1);
		} else {
			if(Integer.parseInt(productType)!=0){
				if (!productService.getParentId(Integer.parseInt(productType))) {
					productList = productService.list(Product.class, MAXPRODUCT, productCurrentPage, session
							.get("WW_TRANS_I18N_LOCALE"), productService
							.getId(Integer.parseInt(productType)));
				} else {
					productList = productService.getProductList(MAXPRODUCT, productCurrentPage, session
							.get("WW_TRANS_I18N_LOCALE"), Integer
							.parseInt(productType));
				}
				u = new Util("product", MAXPRODUCT, Integer.parseInt(productType),session.get("WW_TRANS_I18N_LOCALE"));
			}else{
				productList = productService.getProductList(MAXPRODUCT, productCurrentPage, session
						.get("WW_TRANS_I18N_LOCALE"), -1);
			}
		}
		// 设置当前页面
		u.setYe(productCurrentPage);

		/** 把分页request */
		request.setAttribute("fenye", u);
		request.setAttribute("productList", productList);
		return SUCCESS;
	}

	@Resource
	public void setInitService(InitService initService) {
		this.initService = initService;
	}

	public String productView() {
		initService.initAll(session);
		
		List<Product> banner=productService.getProductList(10,0,session.get("WW_TRANS_I18N_LOCALE"),-1);
		request.setAttribute("banner", banner);	
		
		String productId = request.getParameter("productId");
		if (productId != null) {
			Product productbean = productService.load(Product.class, Integer
					.parseInt(productId), session.get("WW_TRANS_I18N_LOCALE"));
			request.setAttribute("productbean", productbean);
			return SUCCESS;
		} else {
			session.put("error", "产品显示失败，参数错误！");
			return ERROR;
		}
	}

	public String searchProduct() {
		initService.initAll(session);
		
		List<Product> banner=productService.getProductList(10,0,session.get("WW_TRANS_I18N_LOCALE"),-1);
		request.setAttribute("banner", banner);
		
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(true));
		String productFun = request.getParameter("productFun");
		if (productFun != null) {
			String productWhat = request.getParameter("productWhat").trim();
			if ("date".equals(productFun)) {
				where.put("entity.createDate like ", productWhat);
			} else if ("type".equals(productFun)) {
				Category cate = categoryService.load(Category.class,
						productWhat, session.get("WW_TRANS_I18N_LOCALE"));
				where.put("entity.category.id = ", cate.getId());
			} else if ("model".equals(productFun)) {
				where.put("entity.model like ", productWhat);
			} else if ("name".equals(productFun)) {
				where.put("entity.name like ", productWhat);
			}
			where.put("entity.lang = ", session.get("WW_TRANS_I18N_LOCALE")
					.toString());
			List<Product> productList = productService.list(Product.class, 0,
					9, where, new Object[] { " entity.id desc " });
			request.setAttribute("productList", productList);
			return SUCCESS;
		} else {
			session.put("error", "产品显示失败，参数错误！");
			return ERROR;
		}
	}

	public void recover() throws IOException {
		try {
			String result = "";
			if (product != null) {
				Product e = productService.load(Product.class, product.getId());
				if (e.getCategory().isVisible()) {
					productService.update(Product.class, new Object[] { product
							.getId() }, true);
					result = "{'success':'true', 'msg':'recover'}";
				} else {
					result = "{'success':'false', 'msg':'categoryUnvisible'}";
				}
			} else {
				result = "{'success':'false', 'msg':'null'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Resource
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public Product getProduct() {
		return product;
	}

	public void setProductList(List<Product> productList) {
		this.productList = productList;
	}

	public List<Product> getProductList() {
		return productList;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getFromDate() {
		return fromDate;
	}

	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}

	public String getToDate() {
		return toDate;
	}

	public void setToDate(String toDate) {
		this.toDate = toDate;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getStart() {
		return start;
	}

	public void setProductImage(File[] productImage) {
		this.productImage = productImage;
	}

	public File[] getProductImage() {
		return productImage;
	}

	public void setProductImageFileName(String[] productImageFileName) {
		this.productImageFileName = productImageFileName;
	}

	public String[] getProductImageFileName() {
		return productImageFileName;
	}

	public void setProductImageContentType(String[] productImageContentType) {
		this.productImageContentType = productImageContentType;
	}

	public String[] getProductImageContentType() {
		return productImageContentType;
	}

	@Resource
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Resource
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public ImageService getImageService() {
		return imageService;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getMode() {
		return mode;
	}

	@Resource
	public void setXxxImageService(XxxImageService xxxImageService) {
		this.xxxImageService = xxxImageService;
	}

	public XxxImageService getXxxImageService() {
		return xxxImageService;
	}

	public void setWho(String who) {
		this.who = who;
	}

	public String getWho() {
		return who;
	}

	public void setVisible(String visible) {
		this.visible = visible;
	}

	public String getVisible() {
		return visible;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public String getLang() {
		return lang;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
